package com.estudy.efficiency.autonumber;

import com.alibaba.fastjson.JSONObject;
import com.estudy.efficiency.autonumber.enums.AutoNumberModelEnum;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;

/**
 * 基于ES的RestClient的自动化编号
 * @author tim.xie
 * @date 2023/4/27 11:22
 */
public class EsRestClientAutoNumberGeneration extends AutoNumberGeneration {
    private RestClient restClient;

    private String index;

    private String field;

    public EsRestClientAutoNumberGeneration(RestClient restClient, String index, String field, AutoNumberModelEnum mode) {
        super(mode);
        this.restClient = restClient;
        this.index = index;
        this.field = field;
    }

    public EsRestClientAutoNumberGeneration(RestClient restClient, String index, String field) {
        this.restClient = restClient;
        this.index = index;
        this.field = field;
    }

    @Override
    protected int initNumber(String prefix, String suffix) {
        String reg = formatNullString(prefix) + "([0-9]*)" + formatNullString(suffix);
        String dsl = "{\"query\": {\"regexp\": {\"" + field + "\": \"" + reg + "\"}},\"sort\": {\"" + field + "\": {\"order\": \"desc\"}},\"size\": 1}";
        NStringEntity entity = new NStringEntity(dsl, ContentType.APPLICATION_JSON);
        try {
            Response response = restClient.performRequest("GET", index + "/_search", Collections.singletonMap("pretty", "true"), entity);
            JSONObject.parseObject(getResponseContent(response)).get("hits");
            System.out.printf(getResponseContent(response));
        } catch (IOException e) {
//            e.printStackTrace();
            return 0;
        }
        return 0;
    }

    /**
     * 获取带有返回值的响应数据，例如select查询操作
     *
     * @author xiezhenyu
     * @createTime 2022/04/20 10:05
     * @param response
     * @return
     */
    private static String getResponseContent(Response response) throws UnsupportedOperationException, IOException {
        if (response == null) {
            return null;
        }
        HttpEntity entity = response.getEntity();
        StringBuilder builder = new StringBuilder();
        if (entity != null) {
            InputStream content = entity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(content));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
                builder.append("\n");
            }
        }
        return builder.toString();
    }
}
